import type { Ref } from "vue";
import type { tablePageTy, CrudResultType } from "./type";
import type { AxiosPromise } from "axios";
// import type {} from '@/api/'
export interface requestOptionTy {
  otherFunc?: (...args) => void;
  otherQuery?: any | Ref<any>;
  isMock?: boolean;
  mockData?: any;
  mockDelay?: number;
}
/**
 *
 * @param fetch onload 时调用的接口方法
 * @param options 除请求接口外额外的配置项:
 *    otherQuery 额外的请求参数;
 *    otherFunc 请求方法之外执行的函数
 *    isMock 是否采用模拟数据
 *    mockData 模拟数据
 *    mockDelay 模拟数据延时
 * @returns
 */
export default function <T extends Promise<BaseResType>>(
  fetch: ((current: number, size: number, params?: object) => T) | null,
  options?: requestOptionTy
) {
  /*request*/
  const data: Ref<PickOne<Awaited<T>, "data">> = ref();
  const loading: Ref<boolean> = ref(true);
  const _ = options;
  let queryCache = reactive({});

  const onLoad = async (page: Ref<tablePageTy>, params?) => {
    if (params) {
      queryCache = params;
    }
    loading.value = true;
    const pageRow = unref(page);
    // mock 数据处理
    if (_?.isMock || fetch === null) {
      setTimeout(() => {
        data.value = _?.mockData ?? [];
        pageRow.total = _?.mockData.length ?? 0; // effect
        loading.value = false;
      }, _?.mockDelay ?? 1000);
      return;
    }
    const res = await fetch(
      pageRow.currentPage,
      pageRow.pageSize,
      Object.assign({}, queryCache, unref(_?.otherQuery ?? {}))
    );
    data.value = res?.data?.records ?? res?.data ?? [];
    pageRow.total = res?.data?.total ?? 0; // effect
    loading.value = false;
    loading.value = false;
    _?.otherFunc && typeof _.otherFunc === "function" && _.otherFunc();
  };
  return {
    onLoad,
    data,
    loading,
  };
}
